package com.bodacn.keypoint;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapFault;
import org.ksoap2.transport.HttpResponseException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.net.URL;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.view.KeyEvent.ACTION_UP;

public class GuideActivity extends AppCompatActivity implements View.OnClickListener {
    private final static String TAG = GuideActivity.class.getSimpleName();
    private final static int MSG_ChangePSWOver=9001;
    private final static int MSG_LoginCheckOver=9002;
    private final static int MSG_AllowScan=9003;
    private final static int MSG_CheckNetWork=9005;
    private Button btn_LoginSYS, btn_ExitSYS;
    private ImageButton btn_guide_setup;
    private EditText edit_LoginUserNo,edit_LoginPassword,edit_CardNo;
    private TextView txt_CPUID,txt_SoftVer;
    FrameLayout mFlContainer,mFlCardBack,mFlCardFront;
    LinearLayout linerCardBack,linerCardFront;
    private AnimatorSet mRightOutSet; // 右出动画
    private AnimatorSet mLeftInSet; // 左入动画
    public static boolean mIsShowBack,NeedUpdate=false;
    /* 保存解析的XML信息 */
    HashMap<String, String> ServerConfig;
    //全局提示;
    Toast curToast;
    //全局变量
    String STORE_NAME = "Settings";
    String serviceUrl="http://192.168.199.186/BDCOMM";
    String apiUrl="";
    String boardNo="00000";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String CPUID,curLoginUserNo,curLoginUser,curFactory, curDepartNo,curDepart,curLoginTime ,language="中文",curUserPower,curTime,WorkSection;//操作员所属部门等信息;
    int curOperateTime =600,spaceSec=15,switchCount=5;//工作分钟
    int curPlaceCount=30;//工位数;
    String SQLAddr="",SQLUser="",SQLPsw="",SQLDBName="";
    private JSONArray loginJSONArray;//用于接收登陆返回信息;
    private ProgressDialog waitDialog = null;
    boolean ScanSign=false;//执行过程中
    private Timer timer;
    private TimerTask timetask;
    private Context mContext;
    //核心设置的代码
    protected void switchLanguage() {

        //读取配置文件-设置语言
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        serviceUrl=settings.getString("serviceUrl",serviceUrl);
        apiUrl=settings.getString("apiUrl",apiUrl);
        boardNo=settings.getString("boardNo",boardNo);
        WorkSection=settings.getString("WorkSection","SEW");
        language=settings.getString("language",language);
        spaceSec =settings.getInt("spaceSec",spaceSec);
        switchCount=settings.getInt("switchCount",switchCount);
        SQLAddr=settings.getString("SQLAddr",SQLAddr);
        SQLUser=settings.getString("SQLUser",SQLUser);
        SQLPsw=settings.getString("SQLPsw",SQLPsw);
        SQLDBName=settings.getString("SQLDBName",SQLDBName);
        MainApplication.apiUrl=apiUrl;
        //数据连接类赋值;
        MainApplication.ServerIP=SQLAddr;
        MainApplication.UserName=SQLUser;
        MainApplication.Password=SQLPsw;
        MainApplication.DBName=SQLDBName;
        System.out.println("SQLAddr:"+SQLAddr+" SQLUser:"+SQLUser+" SQLPsw:"+SQLPsw+" SQLDBName:"+SQLDBName);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "mm":
                config.locale = new Locale("mm","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //重设界面语言
        switchLanguage();
        //创建界面;
        setContentView(R.layout.activity_guide);
        initView();
        try {
            String SoftVer=getVersionName();
            txt_SoftVer.setText("VER:"+SoftVer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        hideIM(edit_LoginUserNo);
        //绑定动画;
        setAnimators(); // 设置动画
        setCameraDistance(); // 设置镜头距离
        mIsShowBack = true;//初始界面显正面刷卡,假设当前为反面;
        flipCard(mFlContainer);//先切换下动画
        //用于传参数;
        mContext=this;
        startTimer();
    }


    //启动定时器;
    private void startTimer(){
        if (timer==null) {
            timer = new Timer();
            System.out.println("onCreate timer---------------------------------2.1");
            //定时任务;
            if (timetask == null) {
                timetask = new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = MSG_CheckNetWork;
                        handler.sendMessage(message);
                    }
                };
            }
            System.out.println("onCreate timer---------------------------------2.2");
            timer.schedule(timetask, 1000, 1000);
        }
    }
    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
        System.out.println("startTimer five---------------------------------Start");
    }


    // 设置动画
    private void setAnimators() {
        mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.anim_out);
        mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.anim_in);
        // 设置点击事件
        mRightOutSet.addListener(new AnimatorListenerAdapter() {
            @Override public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                mFlContainer.setClickable(false);
                //显示背面的控件
                setBackCardCompontView(mIsShowBack,true);

            }
        });
        mLeftInSet.addListener(new AnimatorListenerAdapter() {
            @Override public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mFlContainer.setClickable(true);
                //根据要求显示背面的控件
                setBackCardCompontView(mIsShowBack,false);
            }
        });
    }

    // 改变视角距离, 贴近屏幕
    private void setCameraDistance() {
        int distance = 16000;
        float scale = getResources().getDisplayMetrics().density * distance;
        mFlCardFront.setCameraDistance(scale);
        mFlCardBack.setCameraDistance(scale);
    }

    // 翻转卡片
    public void flipCard(View view) {
        hideIM(view);
        // 正面朝上
        if (!mIsShowBack) {
            mRightOutSet.setTarget(mFlCardFront);
            mLeftInSet.setTarget(mFlCardBack);
            mRightOutSet.start();
            mLeftInSet.start();
            mIsShowBack = true;
        } else { // 背面朝上
            mRightOutSet.setTarget(mFlCardBack);
            mLeftInSet.setTarget(mFlCardFront);
            mRightOutSet.start();
            mLeftInSet.start();
            mIsShowBack = false;
        }

    }

    //设置是否显示背面的控件，不然会误按;
    public void setBackCardCompontView(boolean isVisible,boolean isAllShow){
        edit_LoginUserNo.setText("");
        edit_LoginPassword.setText("");
        edit_CardNo.setText("");
        if (isAllShow==true)
        {
            linerCardBack.setVisibility(View.VISIBLE);
            linerCardFront.setVisibility(View.VISIBLE);
        } else {
            if (isVisible == false) {
                linerCardBack.setVisibility(View.INVISIBLE);
                linerCardBack.setVisibility(View.INVISIBLE);
                linerCardFront.setVisibility(View.VISIBLE);
                edit_CardNo.setFocusable(true);
                edit_CardNo.setFocusableInTouchMode(true);
                edit_CardNo.setVisibility(View.VISIBLE);
                edit_CardNo.requestFocus();
                edit_CardNo.requestFocusFromTouch();
            } else {
                linerCardBack.setVisibility(View.VISIBLE);
                linerCardFront.setVisibility(View.INVISIBLE);
                edit_CardNo.setFocusable(false);
                edit_CardNo.setFocusableInTouchMode(false);
                edit_CardNo.setVisibility(View.INVISIBLE);
                edit_CardNo.setInputType(InputType.TYPE_NULL);
            }
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        //mIsShowBack = true;//初始界面显正面刷卡,假设当前为反面;
        //flipCard(mFlContainer);//先切换下动画
        System.out.println("onRestart-mIsShowBack:"+mIsShowBack);
        setBackCardCompontView(mIsShowBack,false);

    }

    private void initView()
    {

        txt_CPUID=findViewById(R.id.txt_CPUID);
        txt_SoftVer=findViewById(R.id.txt_SoftVer);
        //按键;
        btn_LoginSYS=findViewById(R.id.btn_LoginSYS);
        btn_LoginSYS.setOnClickListener(this);
        btn_LoginSYS.setFocusableInTouchMode(false);
        btn_LoginSYS.setFocusable(false);
        btn_ExitSYS =findViewById(R.id.btn_ExitSYS);
        btn_ExitSYS.setOnClickListener(this);
        btn_ExitSYS.setFocusableInTouchMode(false);
        btn_ExitSYS.setFocusable(false);
        btn_guide_setup=findViewById(R.id.btn_guide_setup);
        btn_guide_setup.setOnClickListener(this);
        btn_guide_setup.setFocusableInTouchMode(false);
        btn_guide_setup.setFocusable(false);
        //显示控制;
        edit_CardNo=findViewById(R.id.edit_CardNo);
        edit_CardNo.setFocusable(false);
        edit_CardNo.setInputType(InputType.TYPE_NULL);
        edit_CardNo.setFocusableInTouchMode(false);
        edit_CardNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode== KeyEvent.KEYCODE_ENTER)&&(event.getAction()== ACTION_UP))
                {
                    curToast.cancel();
                    edit_CardNo.setEnabled(false);
                    playRingtone();
                    loginCheck();
                }
                return false;
            }
        });

        edit_LoginUserNo=(EditText)findViewById(R.id.edit_LoginUserNo);
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        edit_LoginUserNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if (event.getKeyCode()== KeyEvent.KEYCODE_ENTER)
                    {
                        edit_LoginPassword.setFocusable(true);
                    }
                }
                if ((keyCode== KeyEvent.KEYCODE_ENTER)&&(edit_CardNo.getText().toString().length()>0))
                {
                    edit_LoginPassword.setFocusable(true);
                    edit_LoginPassword.requestFocus();
                    edit_LoginPassword.requestFocusFromTouch();
                }
                return false;
            }
        });
        edit_LoginUserNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginUserNo.setFocusable(true);
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginPassword,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginUserNo.setFocusableInTouchMode(true);
        edit_LoginUserNo.setFocusable(true);
        edit_LoginUserNo.requestFocus();
        edit_LoginUserNo.requestFocusFromTouch();
        //显示控制;
        edit_LoginPassword=(EditText)findViewById(R.id.edit_LoginPassword);
        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
        edit_LoginPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
                        //1.得到InputMethodManager对象
                        InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                        //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                        IBinder windowToken = edit_LoginPassword.getWindowToken();
                        if (windowToken != null) {
                            imm.hideSoftInputFromWindow(windowToken, 0);
                        }
                        loginCheck();
                    }
                }
                return false;
            }
        });
        edit_LoginPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginPassword.setFocusable(true);
                edit_LoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginPassword,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginPassword.setFocusableInTouchMode(true);
        edit_LoginPassword.setFocusable(true);
        edit_LoginPassword.requestFocus();
        edit_LoginPassword.requestFocusFromTouch();
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //获取机器ID
        CPUID=getLocalCPUID().toUpperCase();
        txt_CPUID.setText(CPUID);
        //登陆卡片;
        mFlContainer=findViewById(R.id.loginframelayout);
        mFlCardBack=findViewById(R.id.main_fl_card_back);
        mFlCardFront=findViewById(R.id.main_fl_card_front);
        linerCardBack=findViewById(R.id.linerCardBack);
        linerCardFront=findViewById(R.id.linerCardFront);
        //提示框pd=new ProgressDialog(this);
        waitDialog= new ProgressDialog(this);
        waitDialog.setTitle(getString(R.string.SystemHint));
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    private void showTips() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.SystemExitConfirm))
                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent exit = new Intent(Intent.ACTION_MAIN);
                        exit.addCategory(Intent.CATEGORY_HOME);
                        exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(exit);
                        System.exit(0);
                        //finish();
                    }

                }).setNegativeButton(getString(R.string.Cancel),

                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    ScanSign=false;
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("LoginCheck")==true)
                        {
                            loginJSONArray=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_LoginCheckOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("ChangePSW")==true)
                        {
                            loginJSONArray=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ChangePSWOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            Log.d("msg","ChangePSW--------------------1");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }


    //检测当前的网络状态

    //API版本23以下时调用此方法进行检测
    //因为API23后getNetworkInfo(int networkType)方法被弃用
    public boolean checkNetState_21(){
        //步骤1：通过Context.getSystemService(Context.CONNECTIVITY_SERVICE)获得ConnectivityManager对象
        ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        //步骤2：获取ConnectivityManager对象对应的NetworkInfo对象
        //NetworkInfo对象包含网络连接的所有信息
        //步骤3：根据需要取出网络连接信息
        //获取WIFI连接的信息
        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        Boolean isWifiConn = networkInfo.isConnected();
        //获取移动数据连接的信息
        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        Boolean isMobileConn = networkInfo.isConnected();
        System.out.println("Wifi是否连接:" + isWifiConn+" 移动数据是否连接:" + isMobileConn);
        return isWifiConn||isMobileConn;
    }

    //API版本23及以上时调用此方法进行网络的检测
    //步骤非常类似
    public boolean checkNetState_21orNew(){
        //获得ConnectivityManager对象
        boolean isConnect=false;
        ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取所有网络连接的信息
        Network[] networks = new Network[0];
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            networks = connMgr.getAllNetworks();
            //用于存放网络连接信息
            StringBuilder sb = new StringBuilder();
            //通过循环将网络信息逐个取出来
            for (int i=0; i < networks.length; i++){
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
                if (isConnect==false) isConnect= networkInfo.isConnected();

            }
        }
        return isConnect;
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_CheckNetWork:
                    boolean networkState=false;
                    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP){
                        networkState=checkNetState_21();
                    }else{
                        networkState=checkNetState_21orNew();
                    }
                    if (networkState==true){
                        stopTimer();
                        ((TextView)findViewById(R.id.tv_NetWork1)).setText("网络已连接");
                        ((TextView)findViewById(R.id.tv_NetWork1)).setTextColor(Color.WHITE);
                        ((TextView)findViewById(R.id.tv_NetWork2)).setText("网络已连接");
                        ((TextView)findViewById(R.id.tv_NetWork2)).setTextColor(Color.WHITE);
                        //读取配置文件;
                        Log.e(TAG,"-----------------------------------------CheckNetWork OK-----------------------------------------");
                        Log.e(TAG,"serviceUrl"+serviceUrl);
                        GetServerConfig(serviceUrl+"/SysConfig.xml");
                        //下载最新的版本文件,检查是否需要升级;
                        AutoUpdate autoupdate = new AutoUpdate(mContext,"com.bodacn.keypoint");
                        autoupdate.CheckWebUpdate(serviceUrl+"/UPDATE/keypoint.xml");
                    } else{
                        Log.e(TAG,"-----------------------------------------CheckNetWork Err-----------------------------------------");
                    }
                    break;

                case MSG_ChangePSWOver:
                    Log.d("msg","ChangePSW--------------------1");
                    try {
                        if (loginJSONArray!=null) {
                            if (loginJSONArray.optJSONObject(0).get("ChangePSW").equals("OK")) {
                                curTime = "";
                                if (loginJSONArray.optJSONObject(0).has("Factory"))
                                    curFactory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                if (loginJSONArray.optJSONObject(0).has("DepartNo"))
                                    curDepartNo = loginJSONArray.optJSONObject(0).get("DepartNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("Depart"))
                                    curDepart = loginJSONArray.optJSONObject(0).get("Depart").toString();
                                if (loginJSONArray.optJSONObject(0).has("PlaceCount"))
                                    curPlaceCount = loginJSONArray.optJSONObject(0).getInt("PlaceCount");
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("OperateTime"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("OperateTime");
                                if (loginJSONArray.optJSONObject(0).has("WorkSection"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("WorkSection");
                                if (loginJSONArray.optJSONObject(0).has("DaliyPower"))
                                    MainApplication.DaliyPower = loginJSONArray.optJSONObject(0).getString("DaliyPower");
                                if (loginJSONArray.optJSONObject(0).has("CheckFactory"))
                                    MainApplication.CheckFactory = loginJSONArray.optJSONObject(0).getString("CheckFactory");
                                //设置系统时间
                                curToast.setText(getString(R.string.ChangPswOKInfo));
                                curToast.show();
                            } else {
                                curToast.setText(getString(R.string.ChangPswErrInfo));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_LoginCheckOver:
                case MSG_AllowScan:
                    edit_CardNo.setEnabled(true);
                    edit_CardNo.setFocusable(true);
                    edit_CardNo.selectAll();
                    try {
                        if (loginJSONArray!=null) {
                            if (loginJSONArray.optJSONObject(0).getString("LoginCheck").equals("OK")) {
                                String curLoginType = "A";//默认为组长登陆;
                                if (loginJSONArray.optJSONObject(0).has("Factory"))
                                    curFactory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                if (loginJSONArray.optJSONObject(0).has("DepartNo"))
                                    curDepartNo = loginJSONArray.optJSONObject(0).get("DepartNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("Depart"))
                                    curDepart = loginJSONArray.optJSONObject(0).get("Depart").toString();
                                if (loginJSONArray.optJSONObject(0).has("PlaceCount"))
                                    curPlaceCount = loginJSONArray.optJSONObject(0).getInt("PlaceCount");
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginTime"))
                                    curLoginTime = loginJSONArray.optJSONObject(0).get("LoginTime").toString();
                                if (loginJSONArray.optJSONObject(0).has("OperateTime"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("OperateTime");
                                if (loginJSONArray.optJSONObject(0).has("LoginType"))
                                    curLoginType = loginJSONArray.optJSONObject(0).getString("LoginType");
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                if (loginJSONArray.optJSONObject(0).has("CurTime"))
                                    curTime = loginJSONArray.optJSONObject(0).getString("CurTime");
                                if (loginJSONArray.optJSONObject(0).has("DaliyPower"))
                                    MainApplication.DaliyPower = loginJSONArray.optJSONObject(0).getString("DaliyPower");
                                if (loginJSONArray.optJSONObject(0).has("CheckFactory"))
                                    MainApplication.CheckFactory = loginJSONArray.optJSONObject(0).getString("CheckFactory");
                                //登陆界面;
                                loginOK(curLoginType);
                            } else {
                                curToast.setText(getString(R.string.PleaseCheckEmpNoPSW));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //当处理初始Fragment，则返回;
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showTips();
        }
        return super.onKeyDown(keyCode, event);
    }

    //登陆校验;
    private void loginCheck(){
        //保存配置文件;
        saveSetup();
        if (NeedUpdate==true) {
            onStart();
            edit_LoginUserNo.setText("");
            edit_LoginPassword.setText("");
            edit_CardNo.setText("");

        } else {
            String tmpPassword = edit_LoginPassword.getText().toString();
            //登陆判断
            if (tmpPassword.length() > 0) {
                // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
                tmpPassword = new String(Base64.encode(tmpPassword.getBytes(), Base64.DEFAULT));
                Log.i("Test", "tmpPassword>>>" + tmpPassword);
            }
            edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
            edit_LoginPassword.setInputType(InputType.TYPE_NULL);
            String SqlComm = "Exec ScenePAD_LoginCheck @UserNo='" + edit_LoginUserNo.getText().toString() + "',@CardNo='" + edit_CardNo.getText().toString() + "',@PassWord='" + tmpPassword.replaceAll("\r|\n", "") + "',@CPUID='" + CPUID + "'";
            if (ScanSign==false) ReadSQLData(SqlComm);
            edit_LoginUserNo.setText("");
            edit_LoginPassword.setText("");
            edit_CardNo.setText("");
        }
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_LoginSYS:
                if (edit_LoginUserNo.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputEmpNo));
                    curToast.show();
                } else loginCheck();
                break;
            case R.id.btn_ExitSYS:
                showTips();
                break;
            case R.id.btn_guide_setup:
                showSetup();
                break;
            case R.id.btn_EditUser:
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginUserNo,InputMethodManager.SHOW_FORCED);
                //changepsw();
                break;
                /*
            case R.id.btn_EditPass:
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm1 = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm1.showSoftInput(edit_LoginPassword,InputMethodManager.SHOW_FORCED);
                //changepsw();
                break;
                */
            default:
                break;
        }

    }

    //登陆成功
    private void loginOK(String LoginType){
        //隐藏键盘
        hideIM(edit_LoginPassword);
        new Thread(){
            public void run(){
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        //跳转前关闭键盘
        Intent mainActivity  = new Intent(GuideActivity.this, MainActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser", curLoginUser);
        paramBundle.putString("LoginTime", curLoginTime);
        paramBundle.putString("CurFactory", curFactory);
        paramBundle.putString("CurDepartNo", curDepartNo);
        paramBundle.putString("CurDepart",curDepart);
        paramBundle.putInt("PlaceCount",curPlaceCount);
        paramBundle.putInt("OperateTime", curOperateTime);
        paramBundle.putString("serviceUrl", serviceUrl);
        paramBundle.putString("serviceUrlExt", serviceUrlExt);
        paramBundle.putString("apiUrl", apiUrl);
        paramBundle.putString("CPUID",CPUID);
        paramBundle.putString("BoardNo",boardNo);
        paramBundle.putString("WorkSection",WorkSection);
        paramBundle.putInt("SpaceSec",spaceSec);
        paramBundle.putInt("SwitchCount",switchCount);
        paramBundle.putString("UserPower",curUserPower);
        paramBundle.putString("language",language);
        mainActivity.putExtras(paramBundle);
        waitDialog.cancel();

        //启动主界面;
        startActivity(mainActivity);


    }

    private void saveSetup(){
        //登陆成功后保存配置;
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putString("LoginUserNo",edit_LoginUserNo.getText().toString());
        set_editor.putString("serviceUrl",serviceUrl);
        set_editor.putString("apiUrl",apiUrl);
        set_editor.putString("boardNo",boardNo);
        set_editor.putString("language",language);
        set_editor.putString("SQLAddr", SQLAddr);
        set_editor.putString("SQLUser", SQLUser);
        set_editor.putString("SQLPsw", SQLPsw);
        set_editor.putString("SQLDBName", SQLDBName);
        set_editor.putString("WorkSection", WorkSection);
        set_editor.putInt("spaceSec",spaceSec);
        set_editor.putInt("switchCount",switchCount);
        MainApplication.apiUrl=apiUrl;
        set_editor.commit();
    }
    private void showSetup(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View guide_setup=inflater.inflate(R.layout.guide_setup, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_serverUrl=guide_setup.findViewById(R.id.text_serverUrl);
        text_serverUrl.setText(serviceUrl);
        final EditText text_ApiUrl=guide_setup.findViewById(R.id.text_ApiUrl);
        text_ApiUrl.setText(apiUrl);
        final RadioGroup languageRG=(RadioGroup)guide_setup.findViewById(R.id.languageRG);
        if (language.equals("zh")==true) languageRG.check(R.id.RB1);
        if (language.equals("en")==true) languageRG.check(R.id.RB2);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.v("tag",text_serverUrl.getText().toString());
                        serviceUrl = text_serverUrl.getText().toString();
                        apiUrl = text_ApiUrl.getText().toString();
                        if (languageRG.getCheckedRadioButtonId() == R.id.RB1) language = "zh";
                        if (languageRG.getCheckedRadioButtonId() == R.id.RB2) language = "en";
                        GetServerConfig(serviceUrl+"/SysConfig.xml");
                        System.out.println("语言:" + "---------------------" + language);
                        saveSetup();
                        hideIM(guide_setup);
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(guide_setup);
                Log.v("tag",getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    //修改密码
    private void changepsw(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View guide_setup=inflater.inflate(R.layout.guide_changepsw, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_password_old=(EditText)guide_setup.findViewById(R.id.text_password_old);
        final EditText text_password_new=(EditText)guide_setup.findViewById(R.id.text_password_new);
        final EditText text_password_new2=(EditText)guide_setup.findViewById(R.id.text_password_new2);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        hideIM(guide_setup);
                        String tmpOldPassword = text_password_old.getText().toString();
                        String tmpNewPassword = text_password_new.getText().toString();
                        String tmpNewPassword2 = text_password_new2.getText().toString();
                        Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword+"----tmpNewPassword>>>" + tmpNewPassword+"----tmpNewPassword2>>>" + tmpNewPassword2);
                        if ((tmpNewPassword.length()>0) && (tmpNewPassword.equals(tmpNewPassword2))) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
                            tmpNewPassword = Base64.encodeToString(tmpNewPassword.getBytes(), Base64.DEFAULT);
                            if (tmpOldPassword.length()>0) tmpOldPassword=Base64.encodeToString(tmpOldPassword.getBytes(), Base64.DEFAULT);
                            Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword+"----tmpNewPassword>>>" + tmpNewPassword);
                            //调用登陆过程;
                            String SqlComm="Exec ScenePAD_ChangePSW @UserNo='" + edit_LoginUserNo.getText().toString() + "',@OldPassWord='"+tmpOldPassword.replaceAll("\r|\n", "")+"',@NewPassWord='"+tmpNewPassword.replaceAll("\r|\n", "")+"'";
                            //调用WebService过程并处理界面更新;
                            ReadSQLData(SqlComm);
                        } else
                        {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText(getString(R.string.PasswordConfirmErr));
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    hideIM(guide_setup);
                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialog,true); // true - 使之可以关闭(此为机关所在，其它语句相同)
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                Log.v("tag",getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    //从网络获取版本升级文件
    public void GetServerConfig(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetServerConfig","文件接收A:---"+serviceUrl);
                try {
                    ParseXmlService service = new ParseXmlService();
                    InputStream inStream = new URL(serviceUrl).openStream();
                    System.out.println("服务器配置文件获取成功....");
                    ServerConfig = service.parseXml(inStream);
                    System.out.println(ServerConfig);
                    System.out.println("服务器配置文件解析成功....");
                    return "OK";
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d(TAG,"获取服务器配置文件异常,错误异常抛出！");
                return "NO";
            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr==null)||(rtnstr=="NO"))
                {
                    Toast.makeText(getApplicationContext(), "版本更新文件下载错误", Toast.LENGTH_LONG).show();
                    return;
                } else Log.d(TAG,"文件获取成功..");
                //判断版本是否相同;
                if (null != ServerConfig)
                {
                    SQLAddr = ServerConfig.get("ServerIP");
                    SQLUser = ServerConfig.get("UserName");
                    SQLPsw = ServerConfig.get("Password");
                    SQLDBName = ServerConfig.get("DBName");
                    MainApplication.ServerIP=SQLAddr;
                    MainApplication.UserName=SQLUser;
                    MainApplication.Password=SQLPsw;
                    MainApplication.DBName=SQLDBName;
                    Log.i(TAG,"SQLAddr:"+SQLAddr+" SQLUser:"+SQLUser+" SQLPsw:"+SQLPsw+" SQLDBName:"+SQLDBName);
                }

            }
        }.execute(params);

    }


    //获取软件版本;
    private String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }


    //获取CPU值
    public static String getLocalCPUID() {
        String resultSerial = "";
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/devices/platform/cpu/uuid");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    resultSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return resultSerial;
    }


}
